//
//  HttpService.m
//  COJoke
//
//  Created by 陈渊佑 on 14/12/18.
//  Copyright (c) 2014年 carlosk. All rights reserved.
//

#import "HttpService.h"
#import "ASIHTTPRequest.h"

@implementation HttpService

#define  isHttpTest NO
#define baseUrl isHttpTest?@"http://localhost:18080/":@"http://co.ibaozhuan.com/"
#define articleUrl [NSString stringWithFormat:@"%@%@",baseUrl,@"littlething/wxArticleSearch/%@"]
//#define articleUrl @"http://co.ibaozhuan.com/littlething/wxArticleSearch/%@"

#define imagesUrl [NSString stringWithFormat:@"%@%@",baseUrl,@"littlething/wxArticleImages/%@"]
+(void)doGetArticleList:(NSString *)openId withBlock:(void (^)(NSArray *articleList))block{

    NSString *url = [NSString stringWithFormat:articleUrl,openId];
    [self conncetGet:url withBlock:^(NSString *content) {
       //处理字典
        NSArray *articles = [COParseTool parserData:content withClass:[NewModel class] withKey:@"result"];
        if (block) {
            block(articles);
        }
    }];
}
//获取图片列表数据
+(void)doGetImageList:(NSString *)title withBlock:(void (^)(NSArray *images))block{
        title = [title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:imagesUrl,title];
    [self conncetGet:url withBlock:^(NSString *content) {
        //处理字典
        if (!content) {
            if (block) {
                block(nil);
            };
            return;
        }
        NSArray *images = [COParseTool parserData:content withClass:[ImageCellModel class] withKey:@"result"];
        if (block) {
            block(images);
        }
    }];
}

+(void)conncetGet:(NSString *)url withBlock:(void (^)(NSString * data1))block{
    
    //拼装url
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    //        request.delegate = self;
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    header[@"Content-Type"]=@"text/javascript; charset=utf-8";
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        [request startSynchronous];
        NSData *responData = request.responseData;
        NSLog(@"获取到数据了=%@",responData);
        NSString* content = [[NSString alloc] initWithData:responData encoding:NSUTF8StringEncoding];
        if (content == nil) {
            content = [responData converGBKString];
        }
//        NSDictionary *data2 = [self jsonContentParseDict:content];
        if (block) {
            block(content);
        }
    });
}

//字符串转换成字段
+ (NSDictionary *)jsonContentParseDict:(NSString *)jsonContent{
    NSError *error = nil;
    if ([NSString isStringEmpty:jsonContent]) {
        return nil;
    }
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonContent dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
    return json;
}
@end
